<template>
    <div class="material-management-container">
        <el-card>
            <!-- 搜索区域 -->
            <template #header>
                <div class="card-header">
                    <span class="header-title">领料单管理</span>
                </div>
            </template>

            <el-space direction="vertical" style="width: 100%; align-items: normal; gap: 15px 0;">
                <!-- 搜索表单 -->
                <el-form :model="formData" ref="formRef" label-width="90px" :inline="true" class="search-form">
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="领料单编号" prop="requisitionCode">
                                <el-input v-model="formData.requisitionCode" placeholder="请输入领料单编号" size="large"
                                    clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="领料单名称" prop="requisitionName">
                                <el-input v-model="formData.requisitionName" placeholder="请输入领料单名称" size="large"
                                    clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="领料日期" prop="requiredTime">
                                <el-date-picker v-model="formData.requiredTime" type="datetime" placeholder="选择日期"
                                    value-format="YYYY-MM-DD HH:mm:ss" size="large" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="领料状态" prop="status">
                                <el-select v-model="formData.status" placeholder="请选择" clearable filterable
                                    size="large" style="width: 100%">
                                    <el-option v-for="item in getStatusType" :key="item.value" :value="item.value" :label="item.label" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="padding-left: 50px;">
                            <el-form-item>
                                <!-- 搜索和重置按钮 -->
                                <el-button type="primary" @click="handleSearch">搜索</el-button>
                                <el-button type="info" :plain=true @click="resetForm">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <!-- 操作按钮区域 -->
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-button @click="toInsert" type="primary" :plain="true">+添加</el-button>
                        <el-button type="success" :plain="true" :disabled="selectedRows.length !== 1"
                            @click="handleUpdate(selectedRows[0])">修改</el-button>
                        <el-button type="danger" :plain="true" :disabled="!selectedRows.length"
                            @click="handleBatchDelete">删除</el-button>
                    </el-col>
                </el-row>

                <!-- 数据表格 -->
                <el-table :data="page.records" style="width: 100%" border @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="领料单编号" prop="requisitionCode" width="120">
                        <template #default="{ row }">
                            <el-link type="primary" @click.stop="openDetailDialog(row)">
                                {{ row.requisitionCode }}
                            </el-link>
                        </template>
                    </el-table-column>
                    <el-table-column label="领料单名称" prop="requisitionName" width="150" />
                    <el-table-column label="生产计划编码" prop="planCode" width="150" />
                    <el-table-column label="客户编号" prop="customerResourcesId" width="120" />
                    <el-table-column label="客户名称" prop="customerResourcesName" width="150" />
                    <el-table-column label="领料日期" prop="requiredTime" width="120" />
                    <el-table-column label="领料状态" prop="status" width="120" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getStatusTagType(row.status)">
                                {{ getStatusText(row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="领料人" prop="applicantId" width="150" />
                    <el-table-column label="操作" width="220" fixed="right" align="center">
                        <template #default="{ row }">
                            <el-button type="success" size="small" @click.stop="handleExecute(row)"
                                :disabled="row.status === 1">
                                {{ row.status === 1 ? '已领取' : '执行领料' }}
                            </el-button>
                            <el-button type="primary" size="small" @click.stop="handleUpdate(row)"
                                :disabled="row.status === 1">
                                修改
                            </el-button>
                            <el-button type="danger" size="small" @click.stop="handleDelete(row)"
                                :disabled="row.status === 1">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-space>

            <!-- 分页组件 -->
            <el-pagination v-model:current-page="page.current" v-model:page-size="page.size"
                :page-sizes="[5, 10, 20, 50]" :total="page.total" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" background>
            </el-pagination>

            <!-- 表单弹窗 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" :destroy-on-close="true"
                @closed="handleDialogClosed">
                <router-view @ref-table="refTable" :data="currentRow"></router-view>
            </el-dialog>

            <!-- 执行领料弹窗 -->
            <el-dialog title="执行领料" v-model="executeDialogVisible" width="500px" :destroy-on-close="true">
                <el-form :model="executeForm" ref="executeFormRef" label-width="100px">
                    <el-form-item label="领料单编号">
                        <el-input v-model="executeForm.requisitionCode" disabled />
                    </el-form-item>
                    <el-form-item label="领料单名称">
                        <el-input v-model="executeForm.requisitionName" disabled />
                    </el-form-item>
                    <el-form-item label="生产计划编码">
                        <el-input v-model="executeForm.planCode" disabled />
                    </el-form-item>
                    <el-form-item label="领料人" prop="applicantId" :rules="[{ required: true, message: '请输入领料人姓名' }]">
                        <el-input v-model="executeForm.applicantId" placeholder="请输入领料人姓名" />
                    </el-form-item>
                    <el-form-item label="领料时间" prop="actualTime" :rules="[{ required: true, message: '请选择领料时间' }]">
                        <el-date-picker v-model="executeForm.actualTime" type="datetime" placeholder="选择领料时间"
                            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                    </el-form-item>
                </el-form>

                <template #footer>
                    <el-button @click="executeDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmExecute" :loading="executing">
                        {{ executing ? '领料中...' : '确认领料' }}
                    </el-button>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/api/request.js'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { data } from 'jquery'

const router = useRouter()

// 搜索表单数据
const formData = ref({
    requisitionCode: '',
    requisitionName: '',
    requiredTime: '',
    status: ''
})

// 分页数据
const page = ref({
    current: 1,
    size: 10,
    total: 0,
    records: []
})

// 选中行数据
const selectedRows = ref([])
const currentRow = ref(null)

// 弹窗控制
const dialogVisible = ref(false)
const executeDialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const executeFormRef = ref(null)

// 执行领料表单
const executeForm = reactive({
    requisitionId: '',
    requisitionCode: '',
    requisitionName: '',
    planCode: '',
    applicantId: '',
    actualTime: '',

})

// 执行状态
const executing = ref(false)

// 加载数据
const loadData = async () => {
    const params = {
        current: page.value.current,
        size: page.value.size,
        ...formData.value
    }
    // 移除空值参数
    Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] == null) {
            delete params[key]
        }
    })
    const res = await request({
        url: "/material-requisition/page",
        method: "get",
        params
    })
    if (res.data) {
        page.value = res.data
        console.log('加载数据成功:', page.value)
    }
}

// 执行领料
const handleExecute = (row) => {
    if (row.status === 1) {
        ElMessage.warning('该领料单已完成领料')
        return
    }
    console.log(row.requisitionCode)
    let data = ref([])
    request({
        url: '/material-requisition/getMaterialByCode',
        method: 'get',
        params: {
            requisitionCode: row.requisitionCode
        }
    }).then(res => {
        console.log(res)
        data.value = res.data

        console.log(data.value)

        // 填充执行表单数据
        Object.assign(executeForm, {
            requisitionId: row.requisitionId,
            requisitionCode: row.requisitionCode,
            requisitionName: row.requisitionName,
            planCode: row.planCode,
            applicantId: row.applicantId,
            actualTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
            materialRequisitionDetails: data.value
        })

        executeDialogVisible.value = true
    })

}

// 确认执行领料
const confirmExecute = async () => {
    try {
        // 表单验证
        await executeFormRef.value.validate()

        executing.value = true
        console.log(executeForm)

        const requestData = ref({
            requisitionId: executeForm.requisitionId,
            applicantId: executeForm.applicantId,
            actualTime: executeForm.actualTime,
            requisitionName: executeForm.requisitionName,
            materialRequisitionDetails: executeForm.materialRequisitionDetails
        })
        console.log('执行领料参数:', requestData)
        await request({
            url: '/material-requisition/execute',
            method: 'post',
            data: requestData.value
        })
        ElMessage.success('领料执行成功')
        executeDialogVisible.value = false
        loadData() // 刷新表格数据
    } catch (error) {
        console.error('执行领料失败:', error)
    } finally {
        executing.value = false
    }
}

// 搜索
const handleSearch = () => {
    page.value.current = 1
    console.log(formData.value)
    loadData()
}

// 重置表单
const resetForm = () => {
    formRef.value?.resetFields()
    handleSearch()
}

// 分页大小改变
const handleSizeChange = (size) => {
    page.value.size = size
    page.value.current = 1
    loadData()
}

// 当前页改变
const handleCurrentChange = (current) => {
    page.value.current = current
    loadData()
}

// 查看详情
const openDetailDialog = (row) => {
    dialogTitle.value = "领料单信息"
    currentRow.value = row
    dialogVisible.value = true
    router.push("/production/material/list")
}

// 弹窗控制
const refTable = () => {
    dialogVisible.value = false
    loadData()
}

// 处理行选中
const handleSelectionChange = (val) => {
    selectedRows.value = val
}

// 添加领料单
const toInsert = () => {
    dialogTitle.value = "新增领料单"
    currentRow.value = null
    dialogVisible.value = true
    router.push('/production/material/insert')
}

// 修改领料单
const handleUpdate = (row) => {
    if (!row) return
    if (row.status === 1) {
        ElMessage.warning('已完成的领料单不能修改')
        return
    }
    dialogTitle.value = "修改领料单"
    currentRow.value = row
    dialogVisible.value = true
    router.push('/production/material/update')
}

// 删除单条数据
const handleDelete = async (row) => {
    if (row.status === 1) {
        ElMessage.warning('已完成的领料单不能删除')
        return
    }

    try {
        await ElMessageBox.confirm(`确定要删除领料单【${row.requisitionName}】吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await request({
            url: `/material-requisition/updateByStatus`,
            method: 'delete',
            params: { requisitionId: row.requisitionId }
        })

        ElMessage.success('删除成功')
        loadData() // 重新加载数据
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (!selectedRows.value.length) return

    // 检查是否有已完成的领料单
    const completedOrders = selectedRows.value.filter(item => item.status === 1)
    if (completedOrders.length > 0) {
        ElMessage.warning('包含已完成的领料单，不能删除')
        return
    }

    try {
        const names = selectedRows.value.map(item => item.requisitionName).join('、')
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条领料单吗?<br>${names}`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
        })

        await request({
            url: '/material-requisition/batchDelete',
            method: 'put',
            data: selectedRows.value
        })

        ElMessage.success('批量删除成功')
        selectedRows.value = []
        loadData() // 重新加载数据
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败')
        }
    }
}

// 处理弹窗关闭
const handleDialogClosed = () => {
    router.push('/production/material')
}

const getStatusType =ref([
    { value: "0", label: '待领取' },
    { value: 1, label: '已领取' },
    { value: 2, label: '已取消' }
])

// 状态标签样式
const getStatusTagType = (status) => {
    const map = {
        0: 'warning',    // 待领取
        1: 'success',    // 已领取
        2: 'danger'      // 已取消
    }
    return map[status] || 'info'
}

// 状态文本
const getStatusText = (status) => {
    const map = {
        0: '待领取',
        1: '已领取',
        2: '已取消'
    }
    return map[status] || '未知'
}

// 组件挂载时加载数据
onMounted(() => {
    loadData()
})
</script>

<style scoped>
.material-management-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-title {
    font-size: 18px;
    font-weight: bold;
}

.search-form {
    margin-bottom: 20px;
}

.action-buttons {
    margin-bottom: 15px;
}

.el-table {
    margin-top: 15px;
}

.el-tag {
    margin: 2px;
}
</style>